package sm.upgrade;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;

import sm.upgrade.api.UpgradePhase;
import sm.util.SMMap;

public class SYSATTACHMENTSUpgrade implements UpgradePhase {

	private static Logger logger = LoggerFactory.getLogger(UpgradePhase.class);

	private HibernateTemplate template;

	public void setTemplate(HibernateTemplate template) {
		this.template = template;
	}

	@Override
	public void upgrade() {
		logger.info("Updating application field in the SYSATTACHMENTS table...");

		List<Object> sysAttachments = template.find(
				"from SYSATTACHMENTS where application=? and type=?",
				new Object[] { "svcCatalog", 3d });
		if (sysAttachments != null) {
			for (Object sysAttachment : sysAttachments) {
				SMMap sysAttachmentMap = (SMMap) sysAttachment;
				String newApplication = "joinsvcDisplay";
				// avoid duplicate key error QCCR1E64082
				Object topic = sysAttachmentMap.get("topic");
				Object segment = sysAttachmentMap.get("segment");
				Object uid = sysAttachmentMap.get("uid");
				List<Object> duplicateSysAttachments = template
						.find("from SYSATTACHMENTS whre application=? and type=? and topic=? and segment=? and uid=?",
								new Object[] { newApplication, 3d, topic,
										segment, uid });
				if (duplicateSysAttachments == null
						|| duplicateSysAttachments.isEmpty()) {
					template.delete("SYSATTACHMENTS", sysAttachmentMap);
					SMMap clonedSysAttachmentMap = (SMMap) sysAttachmentMap
							.clone();
					clonedSysAttachmentMap.put("application", "joinsvcDisplay");
					template.save("SYSATTACHMENTS", clonedSysAttachmentMap);
				}
			}
		}

		logger.info("  Finished updating application field in the SYSATTACHMENTS table.");
	}
}
